package com.lv.common.widget.video_editor

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Handler
import android.util.Log
import com.lv.common.event.VideoEditInfo
import com.lv.common.utils.SaveImageUtils
import java.io.IOException

/**
 * 作者： ygx
 * 创建日期：2024/5/15 4:47 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class VideoExtractFrameAsyncUtils(
    context: Context,
    extractW: Int,
    extractH: Int,
    mHandler: Handler
) {
    private val mHandler: Handler
    private val extractW: Int
    private val extractH: Int
    private val mContext: Context
    fun getVideoThumbnailsInfoForEdit(
        videoPath: String?,
        OutPutFileDirPath: String,
        startPosition: Long,
        endPosition: Long,
        thumbnailsCount: Int
    ) {
        val metadataRetriever = MediaMetadataRetriever()
        val vpath = Uri.parse(videoPath)
        metadataRetriever.setDataSource(mContext, vpath)
        val interval = (endPosition - startPosition) / (thumbnailsCount - 1)
        for (i in 0 until thumbnailsCount) {
            if (stop) {
                Log.d("ExtractFrame", "-------ok-stop-stop-->>>>>>>>>")
                try {
                    metadataRetriever.release()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                break
            }
            val time = startPosition + interval * i
            if (i == thumbnailsCount - 1) {
                if (interval > 1000) {
                    val path = extractFrame(
                        metadataRetriever,
                        endPosition - 800,
                        OutPutFileDirPath
                    )
                    sendAPic(path, endPosition - 800)
                } else {
                    val path =
                        extractFrame(metadataRetriever, endPosition, OutPutFileDirPath)
                    sendAPic(path, endPosition)
                }
            } else {
                val path = extractFrame(metadataRetriever, time, OutPutFileDirPath)
                sendAPic(path, time)
            }
        }
        try {
            metadataRetriever.release()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 成功一张add一张
     *
     * @param path path
     * @param time time
     */
    private fun sendAPic(path: String?, time: Long) {
        val info = VideoEditInfo()
        info.path = path!!
        info.time = time
//        LiveEventBus.get(VideoEditInfo::class.java).post(info)
//        val msg = mHandler.obtainMessage(ExtractFrameWorkThread.MSG_SAVE_SUCCESS);
        val msg = mHandler.obtainMessage()
        msg.what = ExtractFrameWorkThread.MSG_SAVE_SUCCESS
        msg.obj = info
        mHandler.sendMessage(msg)
    }

    private fun extractFrame(
        metadataRetriever: MediaMetadataRetriever,
        time: Long,
        OutPutFileDirPath: String
    ): String? {
        val bitmap = metadataRetriever.getFrameAtTime(
            time * 1000,
            MediaMetadataRetriever.OPTION_CLOSEST_SYNC
        )
        if (bitmap != null) {
            //如果对bitmap进行缩放处理,得到的图片大小很小(1kb左右)但会非常模糊,不缩放图片大小60kb左右图片很清晰
//            Bitmap bitmapNew= scaleImage(bitmap);
            var bitmapNew = bitmap
            val path = SaveImageUtils.saveBitmap(mContext, bitmapNew, OutPutFileDirPath)
            //            String path= VideoUtil.saveImageToSDForEdit(bitmapNew, OutPutFileDirPath, System.currentTimeMillis() + "_" + time + VideoUtil.POSTFIX);
            if (bitmapNew != null && !bitmapNew.isRecycled) {
                bitmapNew.recycle()
                bitmapNew = null
            }
            return path
        }
        return null
    }

    /**
     * 设置固定的宽度，高度随之变化，使图片不会变形
     *
     * @param bm Bitmap
     * @return Bitmap
     */
    private fun scaleImage(bm: Bitmap): Bitmap? {
        if (bm == null) {
            return null
        }
        val bmap: Bitmap = bm
        val width = bmap.width
        val height = bmap.height
        val scaleWidth = extractW * 1.0f / width
        //        float scaleHeight =extractH*1.0f / height;
        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleWidth)
        val newBm = Bitmap.createBitmap(
            bm, 0, 0, width, height, matrix,
            true
        )
        if (!bmap.isRecycled) {
            bmap.recycle()
//            bm = null
        }
        return newBm
    }

    @Volatile
    private var stop = false

    init {
        this.mHandler = mHandler
        this.extractW = extractW
        this.extractH = extractH
        this.mContext = context
    }

    fun stopExtract() {
        stop = true
    }
}